from app.mapper.database import db,StudInfo
# import ast

class StudentService:
    def __init__(self):
        pass

    def select_all_stud(self,page):
        per_page = 5  # 每页显示的数量
        count = StudInfo.query.count()
        studs = StudInfo.query.paginate(page=page, per_page=per_page, error_out=False)
        studs_dict_list = [stud.to_json() for stud in studs]

        return {"data":studs_dict_list,"count":count}
    
    def add_stud(self,stud):
        try:
            db.session.add(stud)
            db.session.commit()
            return {"msg":"success","status":"true"}
        except Exception:
            db.session.rollback()
            return {"msg":"error","status":"false"}
    
    def deelete_by_id(self,studid):
        stud = StudInfo.query.filter(StudInfo.StudNo == studid).first()
        if stud:
            try:
                # print(stud.to_json())
                db.session.delete(stud)
                db.session.commit()
                return {"msg":"success","status":"true"}
            except Exception:
                db.session.rollback()
                return {"msg":"error","status":"false"}
        else:
            return {"msg":"用户不存在","status":"false"}
        

    def edit_stud(self,newstud):
        stud = StudInfo.query.filter(StudInfo.StudName == newstud.StudName).first()
        if stud:
            try:
                stud.StudName = newstud.StudName
                stud.StudSex = newstud.StudSex
                stud.Email = newstud.Email
                db.session.commit()
                return {"msg":"success","status":"true"}
            except Exception:
                db.session.rollback()
                return {"msg":"error","status":"false"}
        else:
            return {"msg":"用户不存在","status":"false"}
        
    def select_by_studname(self,username):
        stud = StudInfo.query.filter(StudInfo.StudName == username).first()
        if stud:
            return {"msg":"success","status":"true","data":stud.to_json()}
        else:
            return {"msg":"用户不存在","status":"false"}
        